import React, { useState, useRef } from 'react'
import Webcam from 'react-webcam'
import { List, Button } from 'antd'
import { putObject } from '~/components/my-upload'
import { handlePictures } from '~/api/upload-item-api'

const selectMap = new Map()
const storePics = new Map()

const userInfo = JSON.parse(localStorage.getItem('u')!) || {}

const videoConstraints = {
  width: 960,
  height: 960,
  facingMode: 'user'
}

const WebcamCapture = () => {
  const webcamRef = useRef(null)
  const [imgUrl, setImgUrl] = useState<any>([])

  //base64转blob
  const dataURLtoFile = (dataurl: string) => {
    const arr = dataurl.split(',')
    const mime = arr[0].match(/:(.*?);/)![1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    const blob = new File([u8arr], 'file', { type: mime })
    return blob
  }

  const onClickImg = async (item: any, index: number) => {
    const files = dataURLtoFile(item)
    selectMap.set(index, !selectMap.get(index))
    const isSelected = selectMap.get(index)
    if (isSelected) {
      const data = await putObject({ files, fileType: 'png', frontend: 'frontendpic' })
      storePics.set(index, {
        name: data.fileName,
        storeId: data.storeId
      })
    }
    setImgUrl([...imgUrl])
  }

  const onClickAssociatedPicture = async () => {
    await handlePictures({
      createCompanyCode: userInfo.companyCode,
      createCompanyName: userInfo.companyName,
      createDepartmentCode: userInfo.departmentCode,
      createDepartmentName: userInfo.departmentName,
      createUserName: userInfo.userName,
      createUserNo: userInfo.userNo,
      storePics: [...storePics.values()]
    })
  }

  const capture = () => {
    const imageSrc: any = (webcamRef.current! as any).getScreenshot()
    imgUrl.push(imageSrc)
    setImgUrl([...imgUrl])
  }
  console.log('imgUrl', imgUrl)

  return (
    <div style={{ display: 'flex' }}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <Webcam
          audio={false}
          height="100%"
          mirrored={true}
          ref={webcamRef}
          screenshotFormat="image/jpeg"
          width={960}
          videoConstraints={videoConstraints}
        />
        <Button size="large" type="primary" style={{ width: 100, marginTop: 30 }} onClick={capture}>
          拍照
        </Button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1 }}>
        <List
          style={{ height: 700, overflow: 'scroll' }}
          itemLayout="horizontal"
          dataSource={imgUrl}
          renderItem={(item: any, index: number) => (
            <List.Item>
              <img
                onClick={() => onClickImg(item, index)}
                width={200}
                src={item}
                style={{
                  width: 300,
                  marginLeft: 20,
                  cursor: 'pointer',
                  border: selectMap.get(index) ? '3px solid red' : 'none'
                }}
              />
            </List.Item>
          )}
        />
        <Button size="large" type="primary" style={{ width: 100, marginTop: 30 }} onClick={onClickAssociatedPicture}>
          关联图片
        </Button>
      </div>
    </div>
  )
}

export default WebcamCapture
